//
//  WhiteNoiseGenerator.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/1.
//

import Foundation
import AVFoundation

class WhiteNoiseGenerator {
    
    private var engine = AVAudioEngine()
    private var player = AVAudioPlayerNode()
    
    init() {
        setupAudioEngine()
    }
    
    private func setupAudioEngine() {
        engine.attach(player)
        engine.connect(player, to: engine.mainMixerNode, format: nil)
        
        do {
            try engine.start()
        } catch let error {
            print("Error starting audio engine: \(error.localizedDescription)")
        }
    }
    
    func start() {
        let bufferSize = 44100 // Buffer size in samples
        let format = AVAudioFormat(standardFormatWithSampleRate: 44100.0, channels: 1)!
        
        player.installTap(onBus: 0, bufferSize: AVAudioFrameCount(bufferSize), format: format) { buffer, _ in
            let channelBuffer = buffer.floatChannelData![0]
            for i in 0..<Int(buffer.frameLength) {
                // Generate white noise
                channelBuffer[i] = Float.random(in: -1.0...1.0)
            }
        }
        
        player.play()
    }
    
    func stop() {
        player.stop()
        engine.stop()
    }
}
